﻿
namespace SeedObject
{

    using Serializable = System.SerializableAttribute;
    using XmlIgnoreAttribute = System.Xml.Serialization.XmlIgnoreAttribute;
    using IXmlSerializable = System.Xml.Serialization.IXmlSerializable;

    public delegate void Action();
    public delegate TReturn Action<TReturn, TContext>(TContext obj);

    [Serializable]
    public abstract class Action<T> : Seed, IContext<T>
        where T : ISeed
    {
        #region IContext<T> Members
        private T _Context;
        [XmlIgnoreAttribute]
        public T Context
        {
            get
            {
                return _Context;
            }
            set
            {
                _Context = value;
            }
        }
        #endregion

        #region IAction<T> Members

        public abstract void Run();

        #endregion

        #region IAction<T> Members

        Trigger _Trigger;
        public Trigger Trigger
        {
            get
            {
                return _Trigger;
            }
            set
            {
                _Trigger = value;
            }
        }

        #endregion
    }

    [Serializable]
    public class Actions<T> : Conteiner<Action<T>>, IXmlSerializable
        where T : ISeed
    {
        System.Collections.Generic.Dictionary<Trigger,
            System.Collections.Generic.List<Action<T>>> PoolTriggers =
                new System.Collections.Generic.Dictionary<Trigger,
                    System.Collections.Generic.List<Action<T>>>();
        #region Add
            internal override void Add(Action<T> obj)
            {
                base.Add(obj);
                if (!PoolTriggers.ContainsKey(obj.Trigger))
                    PoolTriggers.Add(obj.Trigger, new System.Collections.Generic.List<Action<T>>());
                PoolTriggers[obj.Trigger].Add(obj);

            }
        #endregion 
        #region Run
            internal void Run(Trigger trigger)
            {
                if(PoolTriggers.ContainsKey(trigger))
                    for (int i = 0; i < PoolTriggers[trigger].Count; i++)
                        PoolTriggers[trigger][i].Run();
            }
        #endregion

        #region IXmlSerializable Members

            public override void ReadXml(System.Xml.XmlReader reader)
            {
                if (reader.IsEmptyElement)
                    return;
                reader.Read();
                base.ReadXml(reader);
                foreach (Action<T> obj in Content.Values)
                {
                    if (!PoolTriggers.ContainsKey(obj.Trigger))
                        PoolTriggers.Add(obj.Trigger, new System.Collections.Generic.List<Action<T>>());
                    PoolTriggers[obj.Trigger].Add(obj);
                }
                reader.ReadEndElement();
            }
        #endregion

    }

}
